package com.anrongtec.zcpt.manager;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.ApkUtils;
import com.art.base.util.AppCacheUtils;
import com.art.base.util.DialogUtil;
import com.art.base.util.FileUtils;
import com.art.base.util.log.LogUtil;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.listener.DownloadListener;
import com.lzy.okhttpserver.task.ExecutorWithListener.OnAllTaskEndListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter.OnItemClickListener;
import com.zhy.adapter.recyclerview.base.ItemViewDelegate;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.utils.DividerDecoration;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 下载管理页面
 * 
 * @ClassName: AppDownManagerActivity
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author dongtianhao
 * @date 2016年8月11日 下午4:44:59
 *
 */
public class AppDownManagerActivity extends BaseActivity implements
		OnAllTaskEndListener {
	private RecyclerView rv_down_manager;
	private List<AppModel> mDatas;
	private StickyRecyclerHeadersDecoration headersDecor;
	private AppDownManageAdapter adapter;
	private DownloadManager downloadManager;
	// 所有的下载任务
	private List<DownloadInfo> allTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_down_manager);
		initViews();
		initData();
	}

	@Override
	protected void initViews() {
		rv_down_manager = (RecyclerView) findViewById(R.id.rv_down_manager);
	}

	@Override
	protected void initData() {
		// 获取到下载信息
//		downloadManager = DownloadService.getDownloadManager();
		downloadManager = APPDownloadManager.getManager();
		downloadManager.getThreadPool().getExecutor()
		.addOnAllTaskEndListener(this);
		allTask = downloadManager.getAllTask();
		sortDowdloadInfo();
		// 设置recycleView的布局属性及header
		rv_down_manager.setLayoutManager(new LinearLayoutManager(this));
		rv_down_manager.addItemDecoration(new DividerDecoration(this));
		// 设置Item增加、移除动画
		rv_down_manager.setItemAnimator(new DefaultItemAnimator());
		adapter = new AppDownManageAdapter(this, allTask);
		// 添加不同header的处理
		adapter.addItemViewDelegate(AppDownManageAdapter.STATUS_DOWNLOADING,
				itemDownloading);
		adapter.addItemViewDelegate(AppDownManageAdapter.STATUS_DOWNLOADED,
				itemDownloaded);
		headersDecor = new StickyRecyclerHeadersDecoration(adapter);
		rv_down_manager.addItemDecoration(headersDecor);
		rv_down_manager.setAdapter(adapter);
		adapter.registerAdapterDataObserver(obs);
		adapter.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
				//				ToastShow.shortMessage(position+"");
			}

			@Override
			public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, final int position) {
				DialogUtil.createAlertDialog(AppDownManagerActivity.this, "删除任务", 0, "是否删除该任务?", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						//						downloadManager.removeTask(allTask.get(position).getTaskKey());
						APPDownloadManager.removeTask(allTask.get(position).getTaskKey());
						adapter.notifyDataSetChanged();
					}
				});
				return true;
			}
		});
		/*adapter.setOnItemLongClick(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, final int position) {

			}
		});*/
	}

	RecyclerView.AdapterDataObserver obs = new RecyclerView.AdapterDataObserver() {
		@Override
		public void onChanged() {
			headersDecor.invalidateHeaders();
		}
	};
	/**
	 * 正在下载的item处理
	 */
	ItemViewDelegate<DownloadInfo> itemDownloading = new ItemViewDelegate<DownloadInfo>() {

		@Override
		public boolean isForViewType(DownloadInfo item, int position) {
			if (item.getState() != DownloadManager.FINISH) {
				return true;
			}
			return false;
		}

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_rv_down_manager;
		}

		@Override
		public void convert(ViewHolder holder, DownloadInfo info, int position) {
			// 一次性更新内容,从缓存处拿到
			AppModel app = (AppModel) AppCacheUtils.getInstance(
					getApplicationContext()).getObject(info.getTaskKey());
			if (app != null) {
				//				holder.setImageUrl(R.id.iv_item_rl_down_app_icon,
				//						app.getIconUrl());
				ImageLoader.getInstance().displayImage(app.getIconUrl(), (ImageView)holder.getView(R.id.iv_item_rl_down_app_icon));
				holder.setText(R.id.tv_item_rv_down_app_name, app.getAppName());
			} else {
				holder.setText(R.id.tv_item_rv_down_app_name,
						info.getFileName());
				Log.w(TAG, "the cache was clear! who do it!");
			}
			// 多次更新内容
			refresh(info, holder);
			DownloadListener downloadListener = new MyDownloadListener();
			downloadListener.setUserTag(holder);
			info.setListener(downloadListener);
		}
	};

	// 对于实时更新的进度ui，放在这里，例如进度的显示，而图片加载等，不要放在这，会不停的重复回调
	// 也会导致内存泄漏
	@SuppressLint("ResourceAsColor")
	private void refresh(final DownloadInfo info, final ViewHolder holder) {
		String downloadLength = Formatter.formatFileSize(
				getApplicationContext(), info.getDownloadLength());
		String totalLength = Formatter.formatFileSize(getApplicationContext(),
				info.getTotalLength());
		// info.setText(downloadLength + "/" + totalLength);
		// LogUtil.trace(Log.DEBUG, TAG, "pro" + info.getProgress());
		// info.getProgress() 属于0~1
		holder.setProgress(R.id.pb_item_rv_down_app,
				(int) (info.getProgress() * 100), 100);
		holder.setText(R.id.tv_item_rv_down_app_total_size, totalLength);
		holder.setText(R.id.tv_item_rv_down_app_current_size, downloadLength);
		if (info.getState() == DownloadManager.NONE) {
			holder.setVisible(R.id.tv_item_rv_down_app_status_msg, false);
			holder.setVisible(R.id.ll_item_rv_down_app_size, true);
		} else if (info.getState() == DownloadManager.PAUSE) {
			holder.setVisible(R.id.tv_item_rv_down_app_status_msg, true);
			holder.setVisible(R.id.ll_item_rv_down_app_size, false);
			holder.setImageResource(R.id.btn_item_rv_down_app_ctrl,
					R.drawable.abc_down_start);
			holder.setText(R.id.tv_item_rv_down_app_status_msg, "下载已暂停");
			holder.setText(R.id.tv_item_rv_down_app_speed, "");
			holder.setVisible(R.id.tv_item_rv_down_app_speed, false);
		} else if (info.getState() == DownloadManager.ERROR) {
			holder.setVisible(R.id.tv_item_rv_down_app_status_msg, true);
			holder.setVisible(R.id.ll_item_rv_down_app_size, false);
			holder.setVisible(R.id.tv_item_rv_down_app_speed, false);
			holder.setImageResource(R.id.btn_item_rv_down_app_ctrl,
					R.drawable.abc_down_start);
			// holder.setText(R.id.tv_item_rv_down_app_status_msg,
			// "下载出错，请重新下载");
			// holder.setTextColor(R.id.tv_item_rv_down_app_status_msg,
			// R.color.red);
		} else if (info.getState() == DownloadManager.WAITING) {
			// holder.setVisible(R.id.tv_item_rv_down_app_status_msg, true);
			// holder.setVisible(R.id.ll_item_rv_down_app_size, false);
			// holder.setText(R.id.tv_item_rv_down_app_status_msg, "等待下载");
		} else if (info.getState() == DownloadManager.FINISH) {
			// 这个应该在已下载中处理
		} else if (info.getState() == DownloadManager.DOWNLOADING) {
			holder.setVisible(R.id.tv_item_rv_down_app_status_msg, false);
			holder.setVisible(R.id.ll_item_rv_down_app_size, true);
			holder.setVisible(R.id.tv_item_rv_down_app_speed, true);
			holder.setImageResource(R.id.btn_item_rv_down_app_ctrl,
					R.drawable.abc_down_pause);
			String networkSpeed = Formatter.formatFileSize(
					getApplicationContext(), info.getNetworkSpeed());
			holder.setText(R.id.tv_item_rv_down_app_speed, networkSpeed + "/s");
		}
		holder.setOnClickListener(R.id.btn_item_rv_down_app_ctrl,
				new OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (info.getState()) {
				case DownloadManager.PAUSE:
					// downloadManager.restartTask(info.getUrl());
//					downloadManager.addTask(info.getTaskKey(),
//							info.getRequest(), info.getListener());
				case DownloadManager.NONE:
				case DownloadManager.ERROR:
					downloadManager.addTask(info.getTaskKey(), info.getRequest(), info.getListener());
					break;
				case DownloadManager.DOWNLOADING:
					downloadManager.pauseTask(info.getTaskKey());
					break;
				case DownloadManager.FINISH:
					break;
				}
				refresh(info, holder);
			}
		});
	}

	private class MyDownloadListener extends DownloadListener {

		@Override
		public void onProgress(DownloadInfo info) {
			if (getUserTag() == null)
				return;
			ViewHolder holder = (ViewHolder) getUserTag();
			refresh(info, holder);
			// holder.refresh(); // 这里不能使用传递进来的 DownloadInfo，否者会出现条目错乱的问题
		}

		@Override
		public void onFinish(DownloadInfo downloadInfo) {
			// Toast.makeText(DownloadManagerActivity.this,
			// "下载完成:" + downloadInfo.getTargetPath(), Toast.LENGTH_SHORT)
			// .show();
			// 先排序
			sortDowdloadInfo();
			adapter.notifyDataSetChanged();
			
			//下载完成后提示安装
			if (FileUtils.isExist(downloadInfo.getTargetPath())) {
				ApkUtils.installSilent(AppDownManagerActivity.this, new File(downloadInfo.getTargetPath()));
//				ApkUtils.install(AppDownManagerActivity.this, new File(downloadInfo.getTargetPath()));
			}
		}

		@Override
		public void onError(DownloadInfo info, String errorMsg, Exception e) {
			ViewHolder holder = (ViewHolder) getUserTag();
			refresh(info, holder);
		}
	}

	
	/**
	 * 已下载的处理
	 */
	ItemViewDelegate<DownloadInfo> itemDownloaded = new ItemViewDelegate<DownloadInfo>() {

		@Override
		public boolean isForViewType(DownloadInfo item, int position) {
			if (item.getState() == DownloadManager.FINISH) {
				return true;
			}
			return false;
		}

		@Override
		public int getItemViewLayoutId() {
			return R.layout.item_app;
		}

		@SuppressLint("ResourceAsColor")
		@Override
		public void convert(ViewHolder holder, final DownloadInfo info,
							int position) {
			// 一次性更新内容,从缓存处拿到
			final AppModel app = (AppModel) AppCacheUtils.getInstance(
					getApplicationContext()).getObject(info.getTaskKey());
//			holder.setTextColor(R.id.tv_item_app_name, R.color.colorAccent_blue);
			if (app != null) {
				holder.setText(R.id.tv_item_app_name, app.getAppName());
				holder.setStar(R.id.ratingbar_item_app_score, app.getScore());

//				holder.setImageUrl(R.id.iv_item_app_icon, app.getIconUrl());
				ImageLoader.getInstance().displayImage(app.getIconUrl(), (ImageView)holder.getView(R.id.iv_item_app_icon));
				String totalLength = Formatter.formatFileSize(
						getApplicationContext(), app.getSize());
				holder.setText(R.id.tv_item_app_total_size, totalLength);
				holder.setText(R.id.tv_item_app_version_name,
						app.getRemoteVersionName());
				if (ApkUtils.isInstalled(AppDownManagerActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
					holder.setText(R.id.btn_item_app_install, "打开");
				}else {
					if (FileUtils.isExist(info.getTargetPath())) {
						holder.setText(R.id.btn_item_app_install, "安装");
					}else {
						holder.setText(R.id.btn_item_app_install, "下载");
					}
				}
			} else {
				holder.setText(R.id.tv_item_app_name, info.getFileName());
				// holder.setStar(R.id.rv_item_app_score, app.getScore());
				// holder.setImageUrl(R.id.iv_app_item_icon, app.getIconUrl());
				String totalLength = Formatter.formatFileSize(
						getApplicationContext(), info.getTotalLength());
				holder.setText(R.id.tv_item_app_total_size, totalLength);
			}
			holder.setOnClickListener(R.id.btn_item_app_install, new OnClickListener() {
				@Override
				public void onClick(View v) {
					//如果已经安装则打开; 未安装,判断安装包是否存在. 如果存在则安装, 不存在则重新下载;
//					if (ApkUtils.isAvailable(AppDownManagerActivity.this, app.getAppPackName())) {
					if (ApkUtils.isInstalled(AppDownManagerActivity.this, app.getAppPackName(), app.getRemoteVersionCode())) {
						if (!app.getAppPackName().equals(Util.getPackageName(AppDownManagerActivity.this))) {
							if (app.getActivity() == null ||app.getActivity().equals("")) {
								ApkUtils.openAPP(AppDownManagerActivity.this, app.getAppPackName());
							} else {
								//ApkUtils.openDefaultApp(AppDownManagerActivity.this,app.getAppPackName());
                                //liuhui 的无图标启动
								ApkUtils.openAPP(AppDownManagerActivity.this, app.getAppPackName(),
										app.getActivity());
							}
						}
					}else {
						if (FileUtils.isExist(info.getTargetPath())) {
//							ApkUtils.install(AppDownManagerActivity.this, new File(info.getTargetPath()));
							ApkUtils.installSilent(AppDownManagerActivity.this, new File(info.getTargetPath()));
						}else {
							
							DialogUtil.createAlertDialog(AppDownManagerActivity.this, "安装异常", 0, "安装包缺失, 是否重新下载?", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									APPDownloadManager.removeTask(info.getTaskKey());
									APPDownloadManager.addTask(AppDownManagerActivity.this, app, info.getListener());
									adapter.notifyDataSetChanged();
								}
							});
							
						}
					}
				}
			});
		}
	};

	protected void onCreateCustomToolBar(Toolbar toolbar) {
		toolbar.setTitle(R.string.title_activity_app_down_manager);
	};

	@Override
	protected void onResume() {
		super.onResume();
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		adapter.unregisterAdapterDataObserver(obs);
		// 记得移除，否者会回调多次
		downloadManager.getThreadPool().getExecutor()
		.removeOnAllTaskEndListener(this);
	}

	@Override
	public void onAllTaskEnd() {
		LogUtil.trace(Log.DEBUG, TAG, "onAllTaskEnd");
		// for (DownloadInfo downloadInfo : allTask) {
		// if (downloadInfo.getState() != DownloadManager.FINISH) {
		// ToastShow.shortMessage("所有下载任务结束，部分下载未完成");
		// return;
		// }
		// }
		// ToastShow.shortMessage("所有下载任务完成");
	}


	/**
	 * 对任务进行排序
	 */
	private void sortDowdloadInfo(){
		Collections.sort(allTask, new Comparator<DownloadInfo>() {

			@Override
			public int compare(DownloadInfo lhs, DownloadInfo rhs) {
				// if (lhs.getState() == lhs.getState()) {
				// return 0;
				// }
				if (lhs.getState() == DownloadManager.FINISH) {
					return 1;
				}
				return -1;
			}
		});
	}
}
